import 'package:get/get.dart';
import 'package:jverify/jverify.dart';
import 'package:nyh_motorcade_app/entity/company_entity.dart';
import 'package:nyh_motorcade_app/entity/login_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/jverify_utils.dart';
import 'package:nyh_motorcade_app/utils/logger_utils.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/system_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/loading_dialog.dart';

class LoginController extends GetxController {
  bool isLogoLongPress = false;

  bool isAgreePrivacyPolicy = true;

  bool isVerifyInitSuccess = false;

  bool isVerifyEnable = false;

  Jverify jverify = JVerifyUtils.getJVerify();

  @override
  void onReady() {
    super.onReady();
    initJVerifyPlatformState();
  }

  void changePrivacyPolicy() {
    isAgreePrivacyPolicy = !isAgreePrivacyPolicy;
    update();
  }

  void setLogoLongPress(bool isLogoLongPress) {
    this.isLogoLongPress = isLogoLongPress;
    update();
  }

  void initJVerifyPlatformState() {
    jverify.isInitSuccess().then((map) {
      isVerifyInitSuccess = map["result"] ?? false;
      LoggerUtils.logSimple("极光认证初始化SDK接口回调：${map.toString()}");
      update();
      if (isVerifyInitSuccess) {
        //判断当前网络环境是否可以发起认证
        jverify.checkVerifyEnable().then((map) {
          isVerifyEnable = map["result"] ?? false;
          LoggerUtils.logSimple("极光认证网络环境接口回调：${map.toString()}");
          update();
          if (isVerifyEnable) {
            //预登录,提升之后授权页拉起速度
            jverify.preLogin().then((map) {
              LoggerUtils.logSimple("极光认证预取号接口回调：${map.toString()}");
            });
          }
        });
      }
    });
  }

  void oneKeyLoginAuthOrPhoneLogin() {
    if (!isAgreePrivacyPolicy) {
      ToastUtils.toast("请阅读并同意用户隐私协议");
      return;
    }
    if (isVerifyInitSuccess && isVerifyEnable) {
      JVerifyUtils.setCustomAuthorizationView();
      jverify.loginAuth(true).then((map) {
        int code = map["code"] ?? 0;
        String token = map["message"] ?? "";
        String operator = map["operator"] ?? "";
        LoggerUtils.logSimple("loginAuth接口返回数据,code = $code,message = $token,operator = $operator");
        login(code, token);
      });
    } else {
      Get.toNamed(Routes.phoneLogin);
    }
  }

  Future<void> login(int code, String token) async {
    if (code == 6001) {
      ToastUtils.toast("获取手机号失败");
      return;
    }
    //已取消授权登录
    if (code == 6002) {
      return;
    }
    if (code == 6004) {
      ToastUtils.toast("正在请求授权,请稍后再试");
      return;
    }
    if (code == 7002) {
      ToastUtils.toast("正在预登录,请稍后再试");
      return;
    }
    if (code != 6000) {
      ToastUtils.toast("登录失败,code:$code");
      return;
    }
    if (token.isEmpty) {
      ToastUtils.toast("获取不到手机号");
      return;
    }

    SPUtils.saveString(SPUtils.TOKEN, "");
    SPUtils.saveString(SPUtils.COMPANY_ID, "");

    LoadingDialog.showCustomDialog(Get.context);
    httpManager.post(
      Get.context,
      HttpAddress.LOGIN_BY_JPUSH,
      {
        "token": token,
        "oilEngineNo": await SystemUtils.getDeviceId(),
      },
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          LoadingDialog.dismissDialog(Get.context);
          ToastUtils.toast("登录失败");
          return;
        }
        LoginEntity loginEntity = LoginEntity().fromJson(data);
        String? token = loginEntity.token ?? "";
        if (token.isEmpty) {
          LoadingDialog.dismissDialog(Get.context);
          ToastUtils.toast("token为空");
          return;
        }
        SPUtils.saveString(SPUtils.TOKEN, token);
        SPUtils.saveBool(SPUtils.IS_ADMIN, loginEntity.isAdmin ?? false);
        getCompanyList();
      },
      onFail: (code, msg) {
        LoadingDialog.dismissDialog(Get.context);
      },
      onError: (msg) {
        LoadingDialog.dismissDialog(Get.context);
      },
    );
  }

  Future<void> getCompanyList() async {
    httpManager.post(
      Get.context,
      HttpAddress.GET_COMPANY_LIST,
      {},
      isToast: true,
      onSuccess: (data) {
        LoadingDialog.dismissDialog(Get.context);
        if (data == null) {
          ToastUtils.toast("请求失败");
          return;
        }
        if (data is List) {
          List<CompanyEntity> companyList = data.map((element) {
            return CompanyEntity().fromJson((element as Map<String, dynamic>));
          }).toList();
          if (companyList.isEmpty) {
            ToastUtils.toast("您没有用油客户权限,请联系管理员");
            return;
          }
          SPUtils.saveString(SPUtils.COMPANY_ID, companyList.first.id ?? "");
          Get.offNamedUntil(Routes.main, (route) => false, arguments: companyList);
        }
      },
      onFail: (code, msg) {
        LoadingDialog.dismissDialog(Get.context);
      },
      onError: (msg) {
        LoadingDialog.dismissDialog(Get.context);
      },
    );
  }
}
